/**
 * Promise简化回调
 * @param {Function} api [微信api]
 */
export const Promisify = api => (options, ...params) =>
	new Promise((resolve, reject) =>
		api(
			Object.assign({}, options, {
				success: resolve,
				fail: reject
			}),
			...params
		)
	)

/**
 * 设置导航标题
 * @param {String} title [标题]
 */
export const setTitle = title =>
	Promisify(wx.setNavigationBarTitle)({
		title: title.length > 15 ? title.slice(0, 15) + '...' : title
	})

/**
 * 本地存储对象
 */
export const storage = {
	set: (key, value) =>
		Promisify(wx.setStorage)({
			key: key,
			data: value
		}),
	get: key =>
		Promisify(wx.getStorage)({
			key: key
		}).then(({ data }) => data),
	delete: key =>
		Promisify(wx.removeStorage)({
			key: key
		}),
	setSync: (key, value) => wx.setStorageSync(key, value)
}

/**
 * 支付方法
 * @param {Object} wxpayparams [支付参数]
 */
export const payment = wxpayparams =>
	Promisify(wx.requestPayment)({
		timeStamp: wxpayparams.timestamp.toString(),
		nonceStr: wxpayparams.nonceStr,
		package: wxpayparams.package,
		signType: wxpayparams.signType,
		paySign: wxpayparams.paySign
	})

/**
 * 显示模态弹窗
 * @param {String} title [标题]
 * @param {String} content [内容]
 * @param {Boolean} showCancel [是否显示取消按钮]
 * @param {Object} options [其它参数]
 */
export const showModal = (title, content, showCancel = false, options = {}) =>
	Promisify(wx.showModal)(
		Object.assign(
			{},
			{
				title: title,
				content: content,
				showCancel: showCancel,
				confirmColor: '#1abc9c'
			},
			options
		)
	)

/**
 * 显示消息提示框
 * @param {String} title [标题]
 * @param {String} icon [图标]
 * @param {Boolean} mask [遮罩]
 */
export const showToast = (title, icon = 'success', mask = true) =>
	Promisify(wx.showToast)({
		title: title,
		icon: icon,
		mask: mask
	})

/**
 * 选择图片
 * @param {Number} count [数量]
 * @param {String} sizeType [尺寸]
 * @param {String} sourceType [类型]
 */
export const chooseImage = (
	count = 1,
	sizeType = ['original', 'compressed'],
	sourceType = ['album', 'camera']
) =>
	Promisify(wx.chooseImage)({
		count: count,
		sizeType: sizeType,
		sourceType: sourceType
	})

/**
 * 上传文件
 * @param {String} endpoint [接口地址]
 * @param {String} filePath [文件地址]
 * @param {Object} params [参数]
 */
export const uploadFile = (endpoint, filePath, params = {}) => {
	// 获取 ext.json 对象 里的 ext
	const ext = wx.getExtConfigSync()
	return Promisify(wx.uploadFile)({
		url: ext.api_root + '/api/web' + endpoint,
		filePath: filePath,
		name: 'file',
		formData: params
	})
}

/**
 * 跳转地址
 * @param {String} url [地址]
 */
export const navigateTo = url =>
	Promisify(
		wx.navigateTo({
			url
		})
	)

/**
 * 切换navbar
 * @param {String} url [地址]
 */
export const switchTab = url =>
	Promisify(
		wx.switchTab({
			url
		})
	)
